<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Folder, ArrowDown, Connection } from '@element-plus/icons-vue'
import PlantUMLEditor from '@/components/PlantUMLEditor.vue'
import { getDiagramByBizId, saveHtmlDocument, removeImages } from '@/api/plantumlService'

// 目录树数据
const directoryData = ref([
  {
    id: 1,
    name: '项目文档',
    children: [
      {
        id: 2,
        name: '系统设计',
        children: [
          { id: 3, name: '架构设计' },
          { id: 4, name: '数据库设计' }
        ]
      },
      {
        id: 5,
        name: '开发文档',
        children: [
          { id: '4189348ee20a4d98bd2b9720ec8bfdfc', name: 'API文档' },
          { id: 7, name: '用户手册' }
        ]
      }
    ]
  },
  {
    id: 8,
    name: '技术文档',
    children: [
      { id: 9, name: '部署指南' },
      { id: 10, name: '故障排除' }
    ]
  }
])

// 树形配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 当前选中的目录
const currentDirectory = ref(null)

// 编辑器相关
const editorRef = ref(null)
const editor = ref(null)

// UML对话框相关
const showUmlDialog = ref(false)
const umlEditorRef = ref(null)

// 处理节点点击
const handleNodeClick = async (data) => {
  currentDirectory.value = data
  
  try {
    // 调用API获取目录对应的数据
    const response = await getDiagramByBizId(data.id)
    
    if (response && response.code === 200 && response.data) {
      const diagramData = response.data
      
      // 设置富文本编辑器内容
      if (editor.value && diagramData.description) {
        editor.value.txt.html(diagramData.description)
      } else {
        // 如果没有内容，加载默认内容
        loadContent(data.id)
      }
      
      // 存储UML数据，以便在打开UML编辑器时使用
      if (diagramData.umlJson) {
        localStorage.setItem(`uml_data_${data.id}`, diagramData.umlJson)
      }
      
      // 存储UML类型
      if (diagramData.type) {
        localStorage.setItem(`uml_type_${data.id}`, diagramData.type)
      }
      
      // 存储图片ID，用于后续删除旧图片
      if (diagramData.id) {
        localStorage.setItem(`image_id_${data.id}`, diagramData.id)
      }
      
      console.log('加载目录数据成功:', diagramData)
    } else {
      // 如果API没有返回数据，则加载本地存储的内容
      loadContent(data.id)
    }
  } catch (error) {
    console.error('获取目录数据失败:', error)
    ElMessage.error('获取目录数据失败')
    
    // 出错时加载本地存储的内容
    loadContent(data.id)
  }
}

// 加载内容
const loadContent = (directoryId) => {
  // 这里可以从本地存储或API加载内容
  const savedContent = localStorage.getItem(`content_${directoryId}`)
  if (savedContent && editor.value) {
    editor.value.txt.html(savedContent)
  } else if (editor.value) {
    editor.value.txt.html('<p>请在此处编辑内容...</p>')
  }
}

// 保存内容
const saveContent = () => {
  if (currentDirectory.value && editor.value) {
    const content = editor.value.txt.html()
    localStorage.setItem(`content_${currentDirectory.value.id}`, content)
    ElMessage.success('内容已保存')
  }
}

// 保存编辑器内容
const saveEditorContent = async () => {
  if (!currentDirectory.value) {
    ElMessage.warning('请先选择一个目录')
    return
  }
  
  if (!editor.value) {
    ElMessage.warning('编辑器未初始化')
    return
  }
  
  try {
    // 获取编辑器的HTML内容
    const htmlContent = editor.value.txt.html()
    
    // 保存到本地存储
    localStorage.setItem(`content_${currentDirectory.value.id}`, htmlContent)
    
    // 准备要发送的数据 - 调用新的API接口
    const saveData = {
      id: currentDirectory.value.id.toString(),
      content: htmlContent
    }
    
    // 发送到新的服务器接口
    const response = await saveHtmlDocument(saveData)
    
    if (response && response.code === 200) {
      ElMessage.success('内容已保存到服务器')
      console.log('保存成功:', response)
    } else {
      throw new Error(response?.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存内容时出错:', error)
    ElMessage.error(`保存失败: ${error.message || '请重试'}`)
  }
}

// 添加目录
const addDirectory = () => {
  ElMessage.info('添加目录功能待实现')
}

// 处理工具栏命令
const handleToolbarCommand = (command) => {
  switch (command) {
    case 'build-uml':
      openUmlDialog()
      break
  }
}

// 打开UML对话框
const openUmlDialog = () => {
  showUmlDialog.value = true
  
  // 在下一个tick中加载UML数据
  nextTick(() => {
    if (umlEditorRef.value && currentDirectory.value) {
      const directoryId = currentDirectory.value.id
      
      // 尝试获取存储的UML数据
      const savedUmlJson = localStorage.getItem(`uml_data_${directoryId}`)
      const savedUmlType = localStorage.getItem(`uml_type_${directoryId}`)
      
      if (savedUmlJson) {
        try {
          // 解析存储的UML数据
          const umlData = JSON.parse(savedUmlJson)
          
          // 如果组件提供了加载UML数据的方法，调用它
          if (typeof umlEditorRef.value.loadUmlData === 'function') {
            umlEditorRef.value.loadUmlData(umlData)
            console.log('已加载UML数据:', umlData)
          } else {
            console.warn('UML编辑器组件未提供loadUmlData方法')
          }
        } catch (error) {
          console.error('解析UML数据失败:', error)
        }
      }
    }
  })
}

// 处理UML生成
const handleUmlGenerated = (umlData) => {
  // 这里可以处理UML生成的数据
  console.log('UML generated:', umlData)
}

// 处理UML保存成功事件
const handleUmlSaveSuccess = (saveData) => {
  console.log('UML saved successfully:', saveData)
  
  // 如果服务器返回了图片路径，更新编辑器中的图片路径
  if (saveData.serverImagePath && editor.value) {
    const currentContent = editor.value.txt.html()
    if (currentContent && currentContent.includes('<img')) {
      // 查找并替换图片路径
      const updatedContent = currentContent.replace(
        /<img[^>]*src="[^"]*"[^>]*>/g,
        `<img src="${saveData.serverImagePath}" style="max-width: 100%; height: auto;" alt="UML Diagram" />`
      )
      editor.value.txt.html(updatedContent)
      console.log('图片路径已更新为服务器路径:', saveData.serverImagePath)
    }
  }
  
  // 保存成功后，关闭UML对话框
  showUmlDialog.value = false
  ElMessage.success('UML图表保存成功！')
}

// 插入UML到编辑器
const insertUmlToEditor = async () => {
  if (umlEditorRef.value && editor.value) {
    try {
      // 先获取UML图片
      const umlImage = umlEditorRef.value.getUmlImage()
      if (!umlImage) {
        ElMessage.warning('请先生成UML图')
        return
      }
      
      // 检查当前目录是否已有图片
      const currentContent = editor.value.txt.html()
      if (currentContent && currentContent.includes('<img')) {
        // 使用确认对话框提示用户
        ElMessageBox.confirm(
          '当前目录已有图片，插入新图片将替换现有图片。是否继续？',
          '确认插入',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(async () => {
          // 用户确认，先删除旧图片，然后保存并插入
          await proceedWithInsertionAndSave(umlImage)
        }).catch(() => {
          // 用户取消
          ElMessage.info('已取消插入')
        })
      } else {
        // 没有图片，直接执行插入和保存
        await proceedWithInsertionAndSave(umlImage)
      }
    } catch (error) {
      console.error('插入UML图时出错:', error)
      ElMessage.error('插入UML图失败')
    }
  } else {
    ElMessage.warning('编辑器未初始化')
  }
}

// 执行插入和保存的完整流程
const proceedWithInsertionAndSave = async (umlImage) => {
  try {
    // 先删除旧图片（如果有的话）
    if (currentDirectory.value) {
      const oldImageId = localStorage.getItem(`image_id_${currentDirectory.value.id}`)
      if (oldImageId) {
        try {
          const response = await removeImages(oldImageId)
          if (response && response.code === 200) {
            console.log('旧图片删除成功:', oldImageId)
            // 删除成功后，清除本地存储的图片ID
            localStorage.removeItem(`image_id_${currentDirectory.value.id}`)
          } else {
            console.warn('删除旧图片失败:', response?.msg)
          }
        } catch (error) {
            console.error('删除旧图片时出错:', error)
          }
        }
      }
    
    // 先插入图片到编辑器（使用临时路径，保存后会更新为服务器路径）
    proceedWithInsertion(umlImage)
    
    // 然后打开保存对话框
    if (umlEditorRef.value) {
      umlEditorRef.value.saveDiagram()
    }
  } catch (error) {
    console.error('执行插入和保存流程时出错:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 保存成功后执行插入操作（保留用于兼容性）
const insertUmlToEditorAfterSave = async (serverImagePath) => {
  if (umlEditorRef.value && editor.value) {
    try {
      // 优先使用服务器返回的图片路径，如果没有则获取UML图片
      let umlImage = serverImagePath
      if (!umlImage) {
        umlImage = umlEditorRef.value.getUmlImage()
      }
      if (!umlImage) {
        ElMessage.warning('请先生成UML图')
        return
      }
      
      // 检查当前目录是否已有图片
      const currentContent = editor.value.txt.html()
      if (currentContent && currentContent.includes('<img')) {
        // 使用确认对话框提示用户
        ElMessageBox.confirm(
          '当前目录已有图片，插入新图片将替换现有图片。是否继续？',
          '确认插入',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          // 用户确认，继续插入
          proceedWithInsertion(umlImage)
        }).catch(() => {
          // 用户取消
          ElMessage.info('已取消插入')
        })
      } else {
        // 没有图片，直接插入
        proceedWithInsertion(umlImage)
      }
    } catch (error) {
      console.error('插入UML图时出错:', error)
      ElMessage.error('插入UML图失败')
    }
  } else {
    ElMessage.warning('编辑器未初始化')
  }
}

// 保存UML图表
const saveUmlDiagram = async () => {
  if (!umlEditorRef.value) {
    ElMessage.warning('UML编辑器未初始化')
    return false
  }
  
  try {
    // 调用组件的保存方法
    await umlEditorRef.value.saveDiagram()
    console.log('UML图表已保存')
    return true
  } catch (error) {
    console.error('保存UML图表时出错:', error)
    ElMessage.error('保存UML图表失败')
    return false
  }
}

// 执行图片插入的辅助函数
const proceedWithInsertion = (umlImage) => {
  // 获取当前编辑器内容
  const currentContent = editor.value.txt.html()
  
  // 如果已有图片，先删除现有图片
  if (currentContent && currentContent.includes('<img')) {
    // 使用正则表达式替换所有img标签及其内容
    const contentWithoutImages = currentContent.replace(/<img[^>]*>/g, '')
    
    // 先设置没有图片的内容
    editor.value.txt.html(contentWithoutImages)
  }
  
  // 插入新图片到编辑器，使用代理路径
  const imageSrc = umlImage.startsWith('/profile/') ? umlImage : umlImage
  editor.value.cmd.do('insertHTML', `<img src="${imageSrc}" style="max-width: 100%; height: auto;" alt="UML Diagram" />`)
  
  ElMessage.success('UML图已插入到编辑器，请保存内容')
}

// 处理UML对话框关闭
const handleUmlDialogClose = () => {
  showUmlDialog.value = false
}

// 初始化编辑器
const initEditor = async () => {
  try {
    // 动态导入wangeditor
    const { default: E } = await import('wangeditor')
    
    if (editorRef.value) {
      editor.value = new E(editorRef.value)
      
      // 配置编辑器
      editor.value.config.height = 500
      editor.value.config.placeholder = '请在此处编辑内容...'
      
      // 配置工具栏
      editor.value.config.menus = [
        'head',
        'bold',
        'fontSize',
        'fontName',
        'italic',
        'underline',
        'strikeThrough',
        'foreColor',
        'backColor',
        'link',
        'list',
        'justify',
        'quote',
        'emoticon',
        'image',
        'table',
        'video',
        'code',
        'undo',
        'redo'
      ]
      
      // 创建编辑器
      editor.value.create()
      
      // 监听内容变化，自动保存
      editor.value.config.onchange = () => {
        if (currentDirectory.value) {
          const content = editor.value.txt.html()
          localStorage.setItem(`content_${currentDirectory.value.id}`, content)
        }
      }
      
      // 设置初始内容
      editor.value.txt.html('<p>请在此处编辑内容...</p>')
    }
  } catch (error) {
    console.error('初始化编辑器失败:', error)
    ElMessage.error('编辑器初始化失败')
  }
}

// 组件挂载
onMounted(async () => {
  await nextTick()
  await initEditor()
})

// 组件卸载
onUnmounted(() => {
  if (editor.value) {
    editor.value.destroy()
  }
})
</script>

<template>
  <div class="main-page" :class="{ 'uml-dialog-open': showUmlDialog }">
    <!-- 左侧目录树 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <h3>目录树</h3>
        <el-button type="primary" size="small" @click="addDirectory">
          <el-icon><Plus /></el-icon>
        </el-button>
      </div>
      <div class="directory-tree">
        <el-tree
          :data="directoryData"
          :props="treeProps"
          node-key="id"
          :default-expanded-keys="[1]"
          :highlight-current="true"
          :current-node-key="currentDirectory?.id"
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <el-icon><Folder /></el-icon>
              <span>{{ node.label }}</span>
            </span>
          </template>
        </el-tree>
      </div>
    </div>

    <!-- 中间内容区域 -->
    <div class="content-area">
      <!-- 顶部工具栏 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <h2>{{ currentDirectory?.name || '请选择目录' }}</h2>
        </div>
        <div class="toolbar-right">
          <el-button type="success" @click="saveEditorContent">保存内容</el-button>
          <el-dropdown @command="handleToolbarCommand">
            <el-button type="primary">
              工具栏
              <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="build-uml">
                  <el-icon><Connection /></el-icon>
                  构建UML
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 富文本编辑器 -->
      <div class="editor-container">
        <div ref="editorRef" class="editor"></div>
      </div>
    </div>

    <!-- UML构建对话框 -->
    <el-dialog
      v-model="showUmlDialog"
      title="UML可视化构建"
      :fullscreen="true"
      :before-close="handleUmlDialogClose"
      destroy-on-close
      class="uml-dialog"
    >
      <!-- 顶部操作按钮 -->
      <div class="uml-dialog-header-actions">
        <el-button @click="showUmlDialog = false">取消</el-button>
        <el-button type="primary" @click="insertUmlToEditor">插入到编辑器</el-button>
      </div>
      
      <div class="uml-dialog-content">
        <PlantUMLEditor
          ref="umlEditorRef"
          :biz-id="currentDirectory?.id || 1"
          :use-model="true"
          @uml-generated="handleUmlGenerated"
          @save-success="handleUmlSaveSuccess"
        />
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.main-page {
  display: flex;
  width: calc(100vw - 2rem);
  height: 100vh;
  background-color: #f5f5f5;
}

.sidebar {
  width: 280px;
  background-color: white;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  
  .sidebar-header {
    padding: 16px;
    border-bottom: 1px solid #e4e7ed;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    h3 {
      margin: 0;
      color: #303133;
    }
  }
  
  .directory-tree {
    flex: 1;
    padding: 16px;
    overflow-y: auto;
    
    .custom-tree-node {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .el-icon {
        color: #409eff;
      }
    }
  }
}

.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: white;
  margin: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  .toolbar {
    padding: 16px 24px;
    border-bottom: 1px solid #e4e7ed;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .toolbar-left {
      h2 {
        margin: 0;
        color: #303133;
      }
    }
    
    .toolbar-right {
      display: flex;
      gap: 12px;
    }
  }
  
  .editor-container {
    flex: 1;
    padding: 24px;
    overflow-y: auto;
    
    .editor {
      height: 100%;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      
      // wangeditor样式覆盖
      :deep(.w-e-toolbar) {
        border-bottom: 1px solid #dcdfe6;
        z-index: 1 !important;
      }
      
      :deep(.w-e-text-container) {
        height: calc(100% - 40px) !important;
        z-index: 1 !important;
      }
      
      // 修复wangeditor层级问题 - 默认层级
      :deep(.w-e-full-screen-container) {
        z-index: 2000 !important;
      }
      
      :deep(.w-e-panel-container) {
        z-index: 2001 !important;
      }
      
      :deep(.w-e-drop-panel) {
        z-index: 2002 !important;
      }
      
      :deep(.w-e-modal) {
        z-index: 2003 !important;
      }
      
      :deep(.w-e-toast) {
        z-index: 2004 !important;
      }
      
      :deep(.w-e-menu-panel) {
        z-index: 2005 !important;
      }
      
      :deep(.w-e-list-panel) {
        z-index: 2006 !important;
      }
      
      :deep(.w-e-color-panel) {
        z-index: 2007 !important;
      }
      
      :deep(.w-e-table-panel) {
        z-index: 2008 !important;
      }
      
      :deep(.w-e-link-panel) {
        z-index: 2009 !important;
      }
      
      :deep(.w-e-image-panel) {
        z-index: 2010 !important;
      }
      
      :deep(.w-e-video-panel) {
        z-index: 2011 !important;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 自定义树节点样式
:deep(.el-tree-node__content) {
  height: 40px;
  
  &:hover {
    background-color: #f5f7fa;
  }
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #ecf5ff;
  color: #409eff;
}

// UML对话框样式
.uml-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
    height: calc(100vh - 120px);
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
  
  .uml-dialog-content {
    flex: 1;
    overflow: hidden;
  }
  
  // 顶部操作按钮样式
  .uml-dialog-header-actions {
    padding: 16px 24px;
    border-bottom: 1px solid #e4e7ed;
    background-color: #fafafa;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    flex-shrink: 0;
    
    .el-button {
      min-width: 100px;
      font-weight: 500;
    }
    
    .el-button--primary {
      background-color: #409eff;
      border-color: #409eff;
      
      &:hover {
        background-color: #66b1ff;
        border-color: #66b1ff;
      }
    }
  }
  
  // 确保dialog层级高于wangeditor
  :deep(.el-dialog) {
    z-index: 3000 !important;
  }
  
  :deep(.el-dialog__wrapper) {
    z-index: 2999 !important;
  }
}

// 当UML对话框打开时，降低wangeditor的层级
.uml-dialog-open {
  :deep(.w-e-full-screen-container),
  :deep(.w-e-panel-container),
  :deep(.w-e-drop-panel),
  :deep(.w-e-modal),
  :deep(.w-e-toast),
  :deep(.w-e-menu-panel),
  :deep(.w-e-list-panel),
  :deep(.w-e-color-panel),
  :deep(.w-e-table-panel),
  :deep(.w-e-link-panel),
  :deep(.w-e-image-panel),
  :deep(.w-e-video-panel) {
    z-index: 1000 !important;
  }
  
  // 确保编辑器本身的层级也不干扰
  .editor-container {
    :deep(.w-e-toolbar) {
      z-index: 1 !important;
    }
    
    :deep(.w-e-text-container) {
      z-index: 1 !important;
    }
  }
}
</style>
